﻿using HomeWork911.Api.Write.Appliaction.Commond;
using HomeWork911.Domain;
using HomeWork911.ErrorCode;
using HomeWork911.infrastrunceture;
using MediatR;

namespace HomeWork911.Api.Write.Appliaction.CommondHandler
{
    public class UserAddCommondHandler : IRequestHandler<UserAddCommond, ApiResult<int>>
    {
        private readonly IBaseIRepository<User> user;
        private readonly IBaseIRepository<Role> role;
        private readonly IBaseIRepository<RoleUser> roleUser;

        public UserAddCommondHandler(IBaseIRepository<User> user, IBaseIRepository<Role> role, IBaseIRepository<RoleUser> roleUser)
        {
            this.user = user;
            this.role = role;
            this.roleUser = roleUser;
        }

        public async Task<ApiResult<int>> Handle(UserAddCommond request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code=ApiEnum.增加成功;
            result.Msg=ApiEnum.增加成功.ToString();

            User users=new User();
            users.UserName=request.UserName;
            users.Password=request.Password;
            users.UserNikename=request.UserNikename;
            users.Number=request.Number;
            await user.Add(users);

            Role roles=new Role();
            roles.RoleName=request.RoleName;
            await role.Add(roles);

            RoleUser roleUsers=new RoleUser();
            roleUsers.UserId = users.UserId;
            roleUsers.RoleId= roles.RoleId;
            await roleUser.Add(roleUsers);
            return await Task.FromResult(result);
        }
    }
}
